import { computed, ref, onMounted, onUnmounted } from 'vue';
import { useRouter } from 'vue-router'; // Vue Router 导入
import { Acheck } from '@/service/getInfo';

interface AcheckRequestData {
  camera_id: string;
  image: string;
  type: number;
  confidence: number;
  code: string;
  result: boolean;
  is_artificial: boolean;
}

export const checkData = () => {
  const monitorEnabled = ref(true);
  const isQualify = ref('');
  const camera_id = ref('1');
  const serverImage = ref<string | null>(null);
  const finalSelection = ref(0);
  const damageList = [
    { type: 0, name: 'yaozhed' },
    { type: 1, name: 'chongkong' },
    { type: 2, name: 'hanfeng' },
    { type: 3, name: 'yueyawan' },
    { type: 4, name: 'shuiban' },
    { type: 5, name: 'youban' },
    { type: 6, name: 'siban' },
    { type: 7, name: 'yiwu' },
    { type: 8, name: 'yahen' },
    { type: 9, name: 'zhehen' },
  ];

  const currentDate = computed(() => new Date().toLocaleDateString('zh-CN'));
  const router = useRouter(); // 使用 Vue Router
  const cameraFeed = ref<HTMLVideoElement | null>(null);
  let stream: MediaStream | null = null;
  const ws = ref<WebSocket | null>(null);
  const receivedDataList = ref<{ number: string; type: string; isArtificial: boolean ;isQualified:string;}[]>([]);

  const startCamera = async () => {
    try {
      stream = await navigator.mediaDevices.getUserMedia({ video: true });
      if (cameraFeed.value) {
        cameraFeed.value.srcObject = stream;
      }
    } catch (error) {
      console.error("摄像头访问失败:", error);
    }
  };

  const stopCamera = () => {
    if (stream) {
      stream.getTracks().forEach((track) => track.stop());
      stream = null;
    }
  };

  const toggleCamera = () => {
    if (monitorEnabled.value) {
      startCamera();
    } else {
      stopCamera();
    }
  };

  const startWebSocket = () => {
    ws.value = new WebSocket("ws://101.132.89.143:8001/ws/detection/1/");

    ws.value.onopen = () => {
      console.log("WebSocket 连接成功");
      sendFrame();
    };

    ws.value.onmessage = (event: MessageEvent) => {
      const data = JSON.parse(event.data);

      if (data.image) {
        serverImage.value = `data:image/jpg;base64,${data.image.replace(/^data:image\/jpeg;base64,/, '')}`;
        const image = new Image();
        image.src = data.image;
        image.onload = () => {
          const serverCanvas = document.getElementById('serverCanvas') as HTMLCanvasElement;
          if (serverCanvas) {
            const serverCtx = serverCanvas.getContext('2d');
            if (serverCtx) {
              serverCanvas.width = image.width;
              serverCanvas.height = image.height;
              serverCtx.drawImage(image, 0, 0);
            }
          }
        };
      }

      const code = `DATA-${receivedDataList.value.length + 1}`;
      const isQualified = data.type !== undefined && data.type !== null ? '不合格' : '合格';
      receivedDataList.value.push({
        number: code,
        type: data.type ?? "未知类型",
        isArtificial: false,
        isQualified:isQualified,
      });

      console.log("接收数据列表:", receivedDataList.value);

      const sentCodes = new Set<string>();
      if (!sentCodes.has(code)) {
        sentCodes.add(code);
        fetch('http://101.132.89.143:8001/detection/post_data/', {
          method: "POST",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify({
            camera_id: camera_id.value,
            image: data.image,
            type: data.type ?? "检测合格",
            confidence: data.confidence ?? 0.9,
            code: code,
            result: true,
            is_artificial: false,
          }),
        })
          .then(response => response.json())
          .then(res => console.log("数据已发送:", res))
          .catch(error => console.error("发送数据出错:", error));
      }
    };

    ws.value.onerror = (error) => {
      console.error("WebSocket 错误:", error);
    };

    ws.value.onclose = () => {
      console.log("WebSocket 连接关闭");
    };
  };

  const sendFrame = () => {
    if (!ws.value || ws.value.readyState !== WebSocket.OPEN || !cameraFeed.value) {
      console.warn("WebSocket 未连接或摄像头未就绪，无法发送数据");
      return;
    }

    const canvas = document.createElement('canvas');
    const context = canvas.getContext('2d');
    if (!context) return;

    canvas.width = cameraFeed.value.videoWidth;
    canvas.height = cameraFeed.value.videoHeight;
    context.drawImage(cameraFeed.value, 0, 0, canvas.width, canvas.height);
    const imageData = canvas.toDataURL('image/jpg');
    const base64Data = imageData.split(',')[1];
    ws.value.send(JSON.stringify({ camera_id: camera_id.value, image: base64Data }));

    setTimeout(sendFrame, 100);
  };

  const latestNumber = computed(() => {
    return receivedDataList.value.length > 0
      ? receivedDataList.value[receivedDataList.value.length - 1].number
      : "暂无数据";
  });

  const latestType = computed(() => {
    return receivedDataList.value.length > 0
      ? receivedDataList.value[receivedDataList.value.length - 1].type
      : "暂无数据";
  });

  const latestIsQualified= computed(() => {
    return receivedDataList.value.length > 0
      ? receivedDataList.value[receivedDataList.value.length - 1].isQualified
      : "暂无数据";
  });

  const isAcheck = (data: Partial<AcheckRequestData>) => {
    const requestData: AcheckRequestData = {
      camera_id: camera_id.value,
      image: data.image || "",
      type: finalSelection.value,
      confidence: data.confidence ?? 0.9,
      code: latestNumber.value,
      result: true,
      is_artificial: true,
    };

    Acheck(requestData)
      .then((res) => {
        console.log("Acheck 接口返回:", res);
        if (res.code === 200) {
          alert("检测数据提交成功！");
          setTimeout(() => {
            router.push('/analysis'); 
          }, 3000);
        }
      })
      .catch((error) => {
        console.error("Acheck 请求失败:", error);
      });
  };

  onUnmounted(() => {
    stopCamera();
    if (ws.value) {
      ws.value.close();
    }
  });

  return {
    camera_id,
    monitorEnabled,
    finalSelection,
    damageList,
    currentDate,
    cameraFeed,
    toggleCamera,
    isQualify,
    startWebSocket,
    startCamera,
    serverImage,
    receivedDataList,
    latestNumber,
    latestType,
    latestIsQualified,
    isAcheck, // 5秒后跳转
  };
};
